package com.eascs.ticket.configuration.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.eascs.app.context.ConfigContext;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.assertion.util.AssertInfoUtils;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.ftp.FtpConfig;
import com.eascs.common.ftp.FtpHelper;
import com.eascs.common.util.UuidUtil;
import com.eascs.ticket.common.entity.EntityUtil;
import com.eascs.ticket.common.service.BaseSevice;
import com.eascs.ticket.configuration.entity.Attachment;

@Service
public class AttachmentService extends BaseSevice {
	private final Logger logger = LoggerFactory.getLogger(AttachmentService.class);
	public static final String FILE_NAME_BLOB_PASTE = "_blob_paste";
	public static final String FILE_NAME_DATE_FORMAT = "yyyyMMddHHmmss";
	public static final String FILE_PATH_DATE_FORMAT = "yyyy/MM/dd";

	@Inject
	private FtpConfig ftpConfig;

	@Transactional(transactionManager = "ticketTransactionManager")
	public void insertAttachment(Attachment attachment) {
		this.proxyDao.insert(attachment);
	}

	@Transactional(transactionManager = "ticketTransactionManager")
	public Attachment uploadAttachment(MultipartFile file) {
		String id = UuidUtil.generateShortUuid(2);
		String fileName = file.getOriginalFilename();
		if (fileName.startsWith(FILE_NAME_BLOB_PASTE)) {
			fileName = "粘贴截图" + new SimpleDateFormat(FILE_NAME_DATE_FORMAT).format(new Date()) + "_" + UuidUtil.generateUuid8WithMd5() + fileName.substring(FILE_NAME_BLOB_PASTE.length());
		}
		String suffix = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
		// String name = fileName.substring(0, fileName.lastIndexOf("."));
		String filePath = buildFilePath(id, suffix);

		Attachment attachment = new Attachment();
		attachment.setName(fileName);
		attachment.setFilePath(filePath);
		attachment.setViewUrl("/attachment/view?id=" + id);
		attachment.setFileSize(file.getSize());
		attachment.setId(id);
		attachment.setSuffix(suffix);
		EntityUtil.initInsertEntity(attachment);

		try {
			FtpHelper.upload(ftpConfig, file.getInputStream(), filePath);
			logger.debug("upload to {}", filePath);
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		}

		insertAttachment(attachment);
		return attachment;
	}

	private String buildFilePath(String id, String suffix) {
		return ConfigContext.getStringValue("attachment.upload.dir") + "/" + new SimpleDateFormat(FILE_PATH_DATE_FORMAT).format(new Date()) + "/" + id + "." + suffix;
	}

	public Attachment getAttachmentById(String id) {
		Attachment attachment = this.proxyDao.getById(Attachment.class, id);
		AssertInfoUtils.assertNotNull(attachment, "can't load attachment with id:{}", id);
		return attachment;
	}

}
